import { useEffect, useState } from "react"
import UserSearch from "./userSearch/index.jsx"
import UserAction from "./userAction/index.jsx"
import { userList, roleList, userEdit, userDel } from "@/api/index"
import dayjs from "dayjs"

import { Button, Pagination, Space, Table, Tag, Popconfirm, message } from "antd"

const UserInfo = () => {
  const [pageSize, setPageSize] = useState(5)
  const [current, setCurrent] = useState(1)
  const [total, setTotal] = useState(0)
  const [dataSource, setDataSource] = useState([])
  const [userFlag, setUserFlag] = useState(false)
  const [loading, setLoading] = useState(false)
  const [type, setType] = useState("")
  const [dataId, setDateId] = useState("")

  useEffect(() => {
    getUserList({ pageSize, current })
  }, [userFlag])

  const columns = [
    {
      title: "创建时间",
      dataIndex: "create_time",
      key: "create_time",
      fixed: "left",
      width: 200,
      render: (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      title: "用户账号",
      dataIndex: "username",
      width: 150,
      key: "username"
    },
    {
      title: "角色名称",
      dataIndex: "rid",
      width: 200,
      key: "rid",
      render: (rid) => (rid ? rid.name : "")
    },
    {
      title: "用户状态",
      width: 150,
      dataIndex: "status",
      key: "status",
      render: (text) =>
        text === 1 ? (
          <Tag color="#3875f6" bordered>
            正常
          </Tag>
        ) : (
          <Tag color="#f50" bordered>
            停用
          </Tag>
        )
    },
    {
      title: "修改时间",
      width: 200,
      dataIndex: "update_time",
      key: "update_time",
      render: (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      title: "操作",
      key: "operation",
      fixed: "right",
      width: 200,
      render: (_, { _id, username, status }) =>
        username !== "admin" && (
          <Space size={"small"}>
            <a onClick={() => onUserActionClick("edit", _id)}>编辑&分配</a>
            <Popconfirm
              title="是否改变状态"
              onConfirm={() => handleClick("update", _id, !status)}
              okText="确定"
              cancelText="取消"
            >
              {status === 1 ? <a>停用</a> : <a>启用</a>}
            </Popconfirm>
            <Popconfirm
              title="是否要删除"
              onConfirm={() => handleClick("delete", _id)}
              okText="确定"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          </Space>
        )
    }
  ]
  const userSearchColumns = [
    {
      label: "用户账号",
      name: "username",
      type: "input",
      placeholder: "请输入用户账号"
    }
  ]

  const userActionColumns = [
    {
      label: "用户账号",
      dataIndex: "username",
      name: "username",
      type: "input",
      rules: [
        {
          required: true,
          message: "用户账号不能为空"
        },
        {
          max: 10,
          message: "用户账号不能超过13个字"
        },
        {
          min: 3,
          message: "用户账号不能少于5个字"
        }
      ],
      userInfo: {
        placeholder: "请输入用户账号"
      }
    },
    {
      label: "用户密码",
      dataIndex: "password",
      name: "password",
      type: "input.password",
      rules: [
        {
          required: true,
          message: "用户账号不能为空"
        },
        {
          min: 3,
          message: "用户密码不能少于5个字"
        }
      ],
      userInfo: {
        placeholder: "请输入用户密码"
      }
    },
    {
      label: "账号状态",
      name: "status",
      type: "select",
      rules: [
        {
          required: true,
          message: "请选择账号状态"
        }
      ],
      userInfo: {
        placeholder: "请选择账号状态",
        options: [
          {
            title: "禁用",
            value: 0
          },
          {
            title: "正常",
            value: 1
          }
        ]
      }
    }
  ]

  const getUserList = async (value) => {
    setLoading(() => true)
    const { pageData, pageSize, total, current, code } = await userList({ ...value })
    setLoading(() => false)
    setCurrent(() => current)
    setPageSize(() => pageSize)
    const data =
      (pageData &&
        pageData.map((item) => {
          return {
            ...item,
            key: item._id
          }
        })) ||
      []
    setTotal(() => total)
    setDataSource(() => data)
  }
  const onSearchStateChange = (data) => {
    getUserList(data)
  }
  const onUserActionClick = async (types, value) => {
    setUserFlag(() => true)
    setType(() => types)
    setDateId(() => value)
  }
  const onOk = (data) => {
    setUserFlag(() => false)
  }
  // 提示泡
  const handleClick = async (str, id, status) => {
    if (str === "delete") {
      const data = await userDel({ _id: id })
      if (data.code === 200) {
        getUserList({ pageSize, current })
        message.success("删除成功")
      }
    } else if (str === "update") {
      const data = await userEdit({ _id: id, status, update_time: Date.now() })
      if (data.code === 200) {
        getUserList({ pageSize, current })
        message.success("状态改变成功")
      }
    }
  }

  return (
    <div className="user-list" style={{ marginBottom: 56 }}>
      <UserAction
        isActionOpen={userFlag}
        onActionOk={onOk}
        type={type}
        _id={dataId}
        userColumns={userActionColumns}
      />
      <div className="user-list-title">
        <h3>管理员列表</h3>
      </div>
      <div>
        <UserSearch columns={userSearchColumns} onSearch={onSearchStateChange} />
      </div>
      <div style={{ padding: "24px 0px" }}>
        <Button type="primary" onClick={() => onUserActionClick("add", "")}>
          添加
        </Button>
      </div>
      <div className="user-form-list">
        <Table
          loading={loading}
          style={{ height: "335px" }}
          columns={columns}
          dataSource={dataSource || []}
          fixHeight={true}
          scroll={{
            x: 1500,
            y: 335
          }}
          pagination={false}
        />
      </div>
      <Pagination
        total={total}
        current={current}
        pageSize={pageSize}
        showQuickJumper
        onChange={(current, pageSize) => {
          getUserList({ current, pageSize })
        }}
        pageSizeOptions={["2", "5", "10", "20"]}
        showSizeChanger
        onShowSizeChange={(current, pageSize) => {
          getUserList({ current, pageSize })
        }}
        style={{
          marginTop: 24,
          float: "right"
        }}
        showTotal={(total) => `共 ${total} 条数据`}
      />
    </div>
  )
}
export default UserInfo
